package ws.jdbc.concurrent.test.tasks;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * This runnable tries execute an SQL batch on the standard statement.
 *
 * @author Wilson Santos, 36228 <wilson.santos@ua.pt>
 */
public class StatementRunnable implements Runnable {

  /** JDBC connection to create the statements. */
  private static volatile Connection con;
  /** Statement of run the batch. */
  private Statement stmt;
  /** Thread cycle count. */
  private static int cycleCount;
  /** Value to update col1. */
  private int num = 76;
  /** Values to update col2 and col3. */
  private String str1 = "c1", str2 = "c2";
  /** Value to update col4. */
  private float decimal = 6.2f;

  public StatementRunnable() throws SQLException {
    assert con != null;
    stmt = con.createStatement(
            ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
  }

  /**
   * Set the JDBC connection to create the statements.
   *
   * @param con JDBC connection to create the statements.
   */
  public static void setCon(Connection con) {
    StatementRunnable.con = con;
  }
  /**
   * Set Thread cycle count.
   *
   * @param cycleCount Thread cycle count.
   */
  public static void setCycleCount(int cycleCount) {
    assert cycleCount > 0;
    StatementRunnable.cycleCount = cycleCount;
  }

  /**
   * Add several SQL commands to the statement object and them run them.
   */
  public void run() {
    try {
      for (int i = 0; i < cycleCount; i++) {
        stmt.addBatch("UPDATE TestData SET col1=" + num);
        stmt.addBatch("UPDATE TestData SET col2='" + str1 + "'");
        stmt.addBatch("UPDATE TestData SET col3='" + str2 + "'");
        stmt.addBatch("UPDATE TestData SET col4=" + decimal);
      }
      stmt.executeBatch();
    } catch (SQLException ex) {
      ex.printStackTrace();
    }
  }
}
